<template>
  <div class="audit-list">
    <div class="page-header">
      <h1>审核管理</h1>
      <p>管理挂牌信息的审核流程</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card pending">
            <div class="stats-content">
              <div class="stats-number">{{ auditStats.pending }}</div>
              <div class="stats-label">待审核</div>
            </div>
            <el-icon class="stats-icon"><Clock /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card approved">
            <div class="stats-content">
              <div class="stats-number">{{ auditStats.approved }}</div>
              <div class="stats-label">已通过</div>
            </div>
            <el-icon class="stats-icon"><Check /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card rejected">
            <div class="stats-content">
              <div class="stats-number">{{ auditStats.rejected }}</div>
              <div class="stats-label">已拒绝</div>
            </div>
            <el-icon class="stats-icon"><Close /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card total">
            <div class="stats-content">
              <div class="stats-number">{{ auditStats.total }}</div>
              <div class="stats-label">总计</div>
            </div>
            <el-icon class="stats-icon"><Document /></el-icon>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 待审核列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>待审核列表</span>
          <el-button @click="refreshList" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>

      <el-table
        :data="pendingList"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="company_name" label="公司名称" min-width="200" />
        <el-table-column prop="listing_type" label="类型" width="100" />
        <el-table-column prop="registration_city" label="注册地" width="120" />
        <el-table-column label="价格" width="120">
          <template #default="{ row }">
            <span v-if="row.is_negotiable">面议</span>
            <span v-else>{{ row.price ? `${row.price}万` : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发布者" width="120">
          <template #default="{ row }">
            {{ row.publisher?.nickname || '未知' }}
          </template>
        </el-table-column>
        <el-table-column label="发布者手机号" width="130">
          <template #default="{ row }">
            <span v-if="row.publisher?.phone_number" class="phone-number">
              {{ row.publisher.phone_number }}
            </span>
            <span v-else class="no-phone">未填写</span>
          </template>
        </el-table-column>
        <el-table-column label="提交时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="自动发布时间" width="160">
          <template #default="{ row }">
            <span v-if="row.auto_publish_at" class="auto-publish-time">
              {{ formatDate(row.auto_publish_at) }}
            </span>
            <span v-else class="no-auto-publish">需人工审核</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleApprove(row)"
            >
              通过
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleReject(row)"
            >
              拒绝
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="viewDetail(row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="auditDialogVisible"
      :title="auditType === 'approve' ? '审核通过' : '审核拒绝'"
      width="500px"
    >
      <el-form :model="auditForm" label-width="80px">
        <el-form-item label="公司名称">
          <span>{{ currentListing?.company_name }}</span>
        </el-form-item>
        <el-form-item
          label="审核备注"
          :rules="auditType === 'reject' ? [{ required: true, message: '拒绝理由不能为空' }] : []"
        >
          <el-input
            v-model="auditForm.comment"
            type="textarea"
            :rows="4"
            :placeholder="auditType === 'approve' ? '可选填审核备注' : '请填写拒绝理由'"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button
          :type="auditType === 'approve' ? 'primary' : 'danger'"
          @click="confirmAudit"
          :loading="auditLoading"
        >
          确认{{ auditType === 'approve' ? '通过' : '拒绝' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="挂牌信息详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="currentDetailListing" v-loading="detailLoading" class="listing-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="信息ID">
            {{ currentDetailListing.id }}
          </el-descriptions-item>
          <el-descriptions-item label="公司名称">
            {{ currentDetailListing.company_name }}
          </el-descriptions-item>
          <el-descriptions-item label="信息类型">
            <el-tag :type="getTypeTagType(currentDetailListing.listing_type)">
              {{ currentDetailListing.listing_type }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(currentDetailListing.status)">
              {{ currentDetailListing.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="价格">
            <span v-if="currentDetailListing.is_negotiable" class="negotiable">面议</span>
            <span v-else-if="currentDetailListing.price">¥{{ Number(currentDetailListing.price).toLocaleString() }}</span>
            <span v-else class="negotiable">面议</span>
          </el-descriptions-item>
          <el-descriptions-item label="是否可议价">
            <el-tag :type="currentDetailListing.is_negotiable ? 'success' : 'info'">
              {{ currentDetailListing.is_negotiable ? '可议价' : '不可议价' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="注册地区">
            {{ formatLocation(currentDetailListing) }}
          </el-descriptions-item>
          <el-descriptions-item label="成立日期">
            {{ currentDetailListing.establishment_date ? formatDate(currentDetailListing.establishment_date) : '未填写' }}
          </el-descriptions-item>
          <el-descriptions-item label="注册资本">
            {{ currentDetailListing.registered_capital_range || '未填写' }}
          </el-descriptions-item>
          <el-descriptions-item label="实缴状态">
            {{ currentDetailListing.paid_in_status || '未填写' }}
          </el-descriptions-item>
          <el-descriptions-item label="公司类型">
            {{ currentDetailListing.company_type || '未填写' }}
          </el-descriptions-item>
          <el-descriptions-item label="税务状态">
            {{ currentDetailListing.tax_status || '未填写' }}
          </el-descriptions-item>
          <el-descriptions-item label="纳税等级">
            {{ currentDetailListing.tax_grade || '未填写' }}
          </el-descriptions-item>
          <el-descriptions-item label="银行开户">
            {{ currentDetailListing.bank_account_status || '未填写' }}
          </el-descriptions-item>
          <el-descriptions-item label="银行流水">
            {{ currentDetailListing.bank_flow || '未填写' }}
          </el-descriptions-item>
          <el-descriptions-item label="商标">
            <el-tag :type="currentDetailListing.has_trademark ? 'success' : 'info'">
              {{ currentDetailListing.has_trademark ? '有' : '无' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="专利">
            <el-tag :type="currentDetailListing.has_patent ? 'success' : 'info'">
              {{ currentDetailListing.has_patent ? '有' : '无' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="软件著作权">
            <el-tag :type="currentDetailListing.has_software_copyright ? 'success' : 'info'">
              {{ currentDetailListing.has_software_copyright ? '有' : '无' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="车牌">
            <el-tag :type="currentDetailListing.has_license_plate ? 'success' : 'info'">
              {{ currentDetailListing.has_license_plate ? '有' : '无' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="社保">
            <el-tag :type="currentDetailListing.has_social_security ? 'success' : 'info'">
              {{ currentDetailListing.has_social_security ? '有' : '无' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="投标历史">
            <el-tag :type="currentDetailListing.has_bidding_history ? 'success' : 'info'">
              {{ currentDetailListing.has_bidding_history ? '有' : '无' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="发布者">
            {{ currentDetailListing.user?.nickname || '未知' }}
          </el-descriptions-item>
          <el-descriptions-item label="发布者手机号">
            <span v-if="currentDetailListing.user?.phone_number" class="phone-number">
              {{ currentDetailListing.user.phone_number }}
            </span>
            <span v-else class="no-phone">未填写</span>
          </el-descriptions-item>
          <el-descriptions-item label="审核状态" span="2">
            <el-tag :type="getAuditStatusTagType(currentDetailListing.audit_status)">
              {{ getAuditStatusText(currentDetailListing.audit_status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item v-if="currentDetailListing.auto_publish_at" label="自动发布时间" span="2">
            <span class="auto-publish-time">{{ formatDate(currentDetailListing.auto_publish_at) }}</span>
          </el-descriptions-item>
          <el-descriptions-item v-if="currentDetailListing.audit_comment" label="审核备注" span="2">
            <span class="audit-comment">{{ currentDetailListing.audit_comment }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="发布时间" span="2">
            {{ formatDate(currentDetailListing.created_at) }}
          </el-descriptions-item>
        </el-descriptions>

        <div v-if="currentDetailListing.description" class="description-section">
          <h4>详细描述</h4>
          <p class="description-content">{{ currentDetailListing.description }}</p>
        </div>
      </div>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Clock, Check, Close, Document, Refresh } from '@element-plus/icons-vue'
import { listingApi, type Listing } from '@/api/admin'

// 响应式数据
const loading = ref(false)
const auditLoading = ref(false)
const pendingList = ref<Listing[]>([])
const auditStats = reactive({
  pending: 0,
  approved: 0,
  rejected: 0,
  total: 0
})

const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 审核对话框
const auditDialogVisible = ref(false)
const auditType = ref<'approve' | 'reject'>('approve')
const currentListing = ref<Listing | null>(null)
const auditForm = reactive({
  comment: ''
})

// 详情对话框
const detailDialogVisible = ref(false)
const detailLoading = ref(false)
const currentDetailListing = ref<Listing | null>(null)

// 方法
const loadPendingList = async () => {
  try {
    loading.value = true
    const response = await listingApi.getPendingAudit({
      page: pagination.page,
      pageSize: pagination.pageSize
    })

    if (response.success) {
      pendingList.value = response.data
      pagination.total = response.pagination.total
    }
  } catch (error) {
    ElMessage.error('获取待审核列表失败')
  } finally {
    loading.value = false
  }
}

const loadAuditStats = async () => {
  try {
    const response = await listingApi.getAuditStats()
    if (response.success) {
      Object.assign(auditStats, response.data)
    }
  } catch (error) {
    ElMessage.error('获取审核统计失败')
  }
}

const handleApprove = (listing: Listing) => {
  currentListing.value = listing
  auditType.value = 'approve'
  auditForm.comment = ''
  auditDialogVisible.value = true
}

const handleReject = (listing: Listing) => {
  currentListing.value = listing
  auditType.value = 'reject'
  auditForm.comment = ''
  auditDialogVisible.value = true
}

const confirmAudit = async () => {
  if (!currentListing.value) return

  if (auditType.value === 'reject' && !auditForm.comment.trim()) {
    ElMessage.error('拒绝理由不能为空')
    return
  }

  try {
    auditLoading.value = true

    if (auditType.value === 'approve') {
      await listingApi.approve(currentListing.value.id, auditForm.comment)
      ElMessage.success('审核通过成功')
    } else {
      await listingApi.reject(currentListing.value.id, auditForm.comment)
      ElMessage.success('审核拒绝成功')
    }

    auditDialogVisible.value = false
    await refreshList()
  } catch (error) {
    ElMessage.error('审核操作失败')
  } finally {
    auditLoading.value = false
  }
}

const viewDetail = async (listing: Listing) => {
  try {
    detailLoading.value = true
    const response = await listingApi.getDetail(listing.id)
    if (response.success) {
      currentDetailListing.value = response.data
      detailDialogVisible.value = true
    } else {
      ElMessage.error('获取详情失败')
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  } finally {
    detailLoading.value = false
  }
}

const refreshList = async () => {
  await Promise.all([loadPendingList(), loadAuditStats()])
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  loadPendingList()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadPendingList()
}

const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 辅助方法
const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    '公司': 'primary',
    '个体户': 'success',
    '代账户': 'warning'
  }
  return typeMap[type] || 'info'
}

const getStatusTagType = (status: string) => {
  const statusMap: Record<string, string> = {
    '在售': 'success',
    '已售': 'danger',
    '下架': 'warning'
  }
  return statusMap[status] || 'info'
}

const getAuditStatusTagType = (auditStatus: string) => {
  const auditStatusMap: Record<string, string> = {
    'PENDING': 'warning',
    'APPROVED': 'success',
    'REJECTED': 'danger'
  }
  return auditStatusMap[auditStatus] || 'info'
}

const getAuditStatusText = (auditStatus: string) => {
  const auditStatusMap: Record<string, string> = {
    'PENDING': '待审核',
    'APPROVED': '已通过',
    'REJECTED': '已拒绝'
  }
  return auditStatusMap[auditStatus] || auditStatus
}

const formatLocation = (listing: any) => {
  const province = listing.registration_province || ''
  const city = listing.registration_city || ''

  if (!province && !city) {
    return '未填写'
  }

  if (province && city) {
    // 如果省份和城市相同（如北京市、上海市等直辖市），只显示一个
    if (province === city || city.includes(province.replace('市', '').replace('省', '').replace('自治区', ''))) {
      return province
    }
    return `${province} ${city}`
  }

  return province || city
}

// 生命周期
onMounted(() => {
  refreshList()
})
</script>

<style scoped>
.audit-list {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
}

.stats-cards {
  margin-bottom: 20px;
}

.stats-card {
  position: relative;
  overflow: hidden;
}

.stats-content {
  position: relative;
  z-index: 2;
}

.stats-number {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stats-label {
  font-size: 14px;
  color: #909399;
}

.stats-icon {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 48px;
  opacity: 0.1;
}

.stats-card.pending .stats-number { color: #E6A23C; }
.stats-card.approved .stats-number { color: #67C23A; }
.stats-card.rejected .stats-number { color: #F56C6C; }
.stats-card.total .stats-number { color: #409EFF; }

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.auto-publish-time {
  color: #E6A23C;
  font-size: 12px;
}

.no-auto-publish {
  color: #909399;
  font-size: 12px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

/* 详情对话框样式 */
.listing-detail {
  max-height: 600px;
  overflow-y: auto;
}

.description-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.description-section h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 16px;
}

.description-content {
  margin: 0;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #606266;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
}

.negotiable {
  color: #e6a23c;
  font-weight: 500;
}

.auto-publish-time {
  color: #e6a23c;
  font-weight: 500;
}

.audit-comment {
  color: #606266;
  font-style: italic;
}

.phone-number {
  color: #606266;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
}

.no-phone {
  color: #C0C4CC;
  font-style: italic;
  font-size: 12px;
}
</style>
